package com.zkflzl.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkflzl.store.common.BaseResponse;
import com.zkflzl.store.common.ErrorCode;
import com.zkflzl.store.common.ResultUtils;
import com.zkflzl.store.exception.ThrowUtils;
import com.zkflzl.store.mapper.MsgMapper;
import com.zkflzl.store.model.dto.msg.MsgAddRequest;
import com.zkflzl.store.model.dto.msg.MsgListRequest;
import com.zkflzl.store.model.entity.Msg;
import com.zkflzl.store.service.MsgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 21582
 * @description 针对表【tb_msg(管理员消息表)】的数据库操作Service实现
 * @createDate 2024-03-21 20:09:21
 */
@Service
public class MsgServiceImpl extends ServiceImpl<MsgMapper, Msg>
        implements MsgService {

    @Override
    public void addMsg(MsgAddRequest msgAddRequest, HttpServletRequest request) {

        String content = msgAddRequest.getContent();

        Msg msg = new Msg();
        msg.setMsg(content);

        boolean save = save(msg);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "添加消息失败");
    }

    @Override
    public BaseResponse selShop(MsgListRequest msgListRequest, HttpServletRequest request) {
        // 分页信息
        Long current = msgListRequest.getCurrent();
        Long pageSize = msgListRequest.getPageSize();
        String sortField = msgListRequest.getSortField();
        String sortOrder = msgListRequest.getSortOrder();
        Date createTime = msgListRequest.getCreateTime();
        Integer type = msgListRequest.getType();

        if (createTime == null) {
            createTime = new Date();
        }

        Page<Msg> page = new Page<>(current, pageSize);
        QueryWrapper<Msg> queryWrapper = new QueryWrapper<>();
        // 更具时间查询
        if (type == 0) {    // 查询创建时间之前的数据
            queryWrapper.lt("createTime", createTime);
        } else {   // 查询创建时间之后的数据
            queryWrapper.gt("createTime", createTime);
        }
        if (!StringUtils.isBlank(sortField) && !StringUtils.isBlank(sortOrder)) {
            queryWrapper.orderBy(true, "asc".equals(sortOrder), sortField);
        }
        Page<Msg> msgPage = this.page(page, queryWrapper);
        return ResultUtils.success(msgPage);
    }

    @Override
    public void updateShop(Long id, HttpServletRequest request) {

        UpdateWrapper<Msg> msgUpdateWrapper = new UpdateWrapper<>();
        msgUpdateWrapper
                .eq("id", id)
                .setSql("status = 1");
        boolean updated = this.update(msgUpdateWrapper);
        ThrowUtils.throwIf(!updated, ErrorCode.SYSTEM_ERROR, "更新失败");
    }
}




